package _interview150;

/**
 * 64. 最小路径和
 */
public class No64 {
    private int[][] grid;
    private int[][] cache;

    public int minPathSum(int[][] grid) {
        this.grid = grid;
        int m = grid.length;
        int n = grid[0].length;
        cache = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                cache[i][j] = -1;
            }
        }
        return dfs(m - 1, n - 1);
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return Integer.MAX_VALUE / 2;
        else if (i == 0 && j == 0) return grid[0][0];
        else if (cache[i][j] != -1) return cache[i][j];
        else return cache[i][j] = grid[i][j] + Math.min(dfs(i - 1, j), dfs(i, j - 1));
    }
}